<template>
    <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        :address-info="AddressInfo"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="OnSave"
        @delete="OnDelete"
    />
</template>

<script setup>
import { areaList } from '@vant/area-data';

const { proxy } = getCurrentInstance();

const business = proxy.$business;
const addrid = ref(proxy.$route.query.addrid ?? 0);
const AddressInfo = ref({});

onBeforeMount(() =>
{
    GetAddressInfo();
});

const GetAddressInfo = async () =>
{
    const params = {
        busid:business.value.id,
        addrid:addrid.value
    }

    const result = await proxy.$http.post('/address/info',params);

    if(result.code === 1)
    {
        AddressInfo.value = {
            name:result.data.consignee,
            tel:result.data.mobile,
            areaCode:result.data.district ? result.data.district : (result.data.city ? result.data.city : result.data.province),
            addressDetail:result.data.address,
            isDefault:result.data.status == 1 ? true : false
        }
    }else{
        proxy.$fail(result.msg,() => proxy.$router.back());
    }
}

const OnSave = async (values) =>
{
    const params = {
        id:addrid.value,
        busid:business.value.id,
        consignee:values.name,
        mobile:values.tel,
        status:values.isDefault === true ? 1 : 0,
        address:values.addressDetail,
        code:values.areaCode
    }

    const result = await proxy.$http.post('/address/edit',params);

    if (result.code === 1) {
        proxy.$success(result.msg,() => proxy.$router.back());
    }else {
        proxy.$fail(result.msg);
    }
}

const OnDelete = () =>
{
    proxy.$confirm({
        title:'删除',
        message:'是否确认该删除收货地址？'
    }).then(async () => {
        const params = {
            busid:business.value.id,
            addrid:addrid.value
        }

        const result = await proxy.$http.post('/address/del',params);

        if(result.code === 1)
        {
            proxy.$success(result.msg,() => proxy.$router.back());
        }else{
            proxy.$fail(result.msg);
        }
    }).catch((err) => {});
}
</script>